<!-- 课文跟读 -->
<template>
    <AppHeader title="课文同步-Starte…" :banAnimate="true" backgroundColor="#ffffff">
        <template #left>
            <img @click="onClickLeft" src="@/assets/phoneticPractice/返回图标@3x.png" width="9" height="18" />
        </template>
    </AppHeader>
    <div class="container-practice" v-if="practoceList && practoceList.length">
        <div class="container-height"></div>
        <div class="practice-top">
            <div class="practice-top-currentPage">{{ currentPage }}<span>/{{ practoceList.length }}</span></div>
            <div class="practice-top-slider">
                <Slider v-phoneticSymboll="currentPage" min="1" :max="practoceList.length || 1000" active-color="#0CB76C">
                </Slider>
            </div>
            <div class="practice-top-switch">
                <div :class="active ? 'active' : ''" @click="automaticOverlay = true">自动</div>
                <div :class="!active ? 'active' : ''" @click="switchManual">手动</div>
            </div>
        </div>
        <div class="container-text">
            My name's Miss Zhou. My name's Miss Zhou.
            My name's Miss Zhou. My name's Miss Zhou.
            My name's Miss Zhou. My name's Miss Zhou.
            My name's Miss Zhou. My name's Miss Zhou.
            My name's Miss Zhou. My name's Miss Zhou.
        </div>
        <div class="practice-bottom" v-show="!active">
            <div class="practice-bottom-img" @click="previous">
                <img src="@/assets/phoneticPractice/暂停@3x.png" width="18px" @click="playRecording" />
            </div>
            <div class="practice-bottom-start" @click="next">
                播放全文
            </div>
        </div>
    </div>
    <!-- <Overlay :show="automaticOverlay">
        <div class="automaticOverlay">
            <div class="automaticOverlay-context">手动模式可重读跟读，需要您自主操作进行跟读流程,确定切换吗?</div>
            <div class="automaticOverlay-button">
                <div @click="automaticOverlay = false">取消</div>
                <div @click="switchAutomatic">确定</div>
            </div>
        </div>
    </Overlay> -->

    <audio ref="audioElement" :src="audioSrc" @ended="playEnded" preload="auto"></audio>
</template>

<script setup>
import { Slider, Overlay } from "vant";
import AppHeader from '../../components/AppHeader.vue'
import { useRouter, useRoute } from 'vue-router'
import { onMounted, reactive, ref, toRefs, nextTick, watch } from 'vue'
import IatRecorder from '@/utils/iatRecorder'
import { request } from "@/api/request";
import scoreSrcRed from "@/assets/phoneticPractice/分数-红@3x.png"
import scoreSrcYellow from "@/assets/phoneticPractice/分数-黄@3x.png"
import scoreSrcGreed from "@/assets/phoneticPractice/分数-绿@3x.png"

const router = useRouter()
const route = useRoute()
const onClickLeft = () => {
    router.go(-1)
}
const currentPage = ref(1)
const active = ref(0)
const automaticOverlay = ref(false)

const title = route.query.title;
const state = reactive({
    practoceList: [],
    sourceObj: {}
})
const playImgSrc = ref()
const tapeImgSrc = ref()
const bottomImgSrc = ref()
const scoreSrc = ref()
const isPlay = ref(true)
const audioElement = ref(null)
const audioPlayer = ref(null)
const audioSrc = ref('')
const tapeShow = ref(true)
let iatRecorder = new IatRecorder()
let mediaRecorder;
let recordedChunks = [];
let totalTime = 0

watch(currentPage, (newVal) => {

    if (state.practoceList.length) {
        iatRecorder = new IatRecorder({ text: state.practoceList[newVal - 1].words })
    }

}, { immediate: true })



onMounted(async () => {
    totalTime = Date.now();
    initImg()
    state.practoceList = await getMissionAnswerDetail()
    if (state.practoceList && state.practoceList.length) {
        iatRecorder = new IatRecorder({ text: state.practoceList[0].words })
    }
    audioPlayer.value = document.getElementById('audioPlayer');
})
const initImg = async () => {
    const palyModule = await import('@/assets/phoneticPractice/声音@3x.png')
    playImgSrc.value = palyModule.default
    const tapeModule = await import('@/assets/phoneticPractice/录音@3x.png')
    tapeImgSrc.value = tapeModule.default
    const bottomModule = await import('@/assets/phoneticPractice/形状@3x.png')
    bottomImgSrc.value = bottomModule.default
}

const getMissionAnswerDetail = async () => {
    // const res = await request({
    //     url: `https://d-xueer.bigchun.com/api/phonetic/getWords`,
    //     method: 'get'
    // }, {
    //     query: {
    //         // versionId: route.query.versionId
    //         versionId: 1
    //     }
    // })

    // if (res.code == 1) {
    //     return res.data
    // }
    return [
        {
            wordPic: '@/assets/phoneticPractice/录音@3x.png',
            sentences: 'kkkkkkk',
            words: '例如',
            symbol: 'lll',
            pretations: '看见对方接受',
            sourceObj: {
                integrity_score: '鼠须田',
                total_score: '1'
            }
        }
    ]
}

const autoColor = (num) => {
    if (num < 60) {
        return 'autoRed' //#FA192C
    } else if (num > 60 && num < 80) {
        return 'autoYellow'//#FF9917
    } else if (num > 80) {
        return 'autoGreed'//#0CB76C
    }
}
//上一个
const previous = () => {
    if (currentPage.value == 1) return
    if (currentPage.value) currentPage.value--
}
// 下一个
const next = async () => {
    recordedChunks = []
    // let code = await saveFollow()
    // console.log(code);
    // if (code == 1) {
    //     if (currentPage.value == state.practoceList.length) {
    //         let use_time = Math.floor((Date.now() - totalTime) / 1000);
    //         router.push({
    //             path: '/textbookSync/handHomework',
    //             query: {
    //                 title: title,
    //                 versionId: route.query.versionId,
    //                 use_time: use_time
    //             }
    //         })
    //     } else {
    //         currentPage.value++
    //     }

    // }
    router.push({
        path: '/textbookSync/handHomework',
        query: {
            title: 'session'
            // versionId: route.query.versionId,
            // use_time: use_time
        }
    })
}
//保存跟读信息
const saveFollow = async () => {
    let obj = state.practoceList[currentPage.value - 1]
    // let video = await fileToBase64(obj.recordedChunks[0])
    // console.log(video);
    const res = await request({
        url: `https://d-xueer.bigchun.com/api/phonetic/saveFollow`,
        method: 'post'
    }, {
        data: {
            versionId: route.query.versionId,
            wId: obj.wId,
            score: Math.round(obj.sourceObj.total_score),
            integrity: Math.round(obj.sourceObj.integrity_score),
            fluency: Math.round(obj.sourceObj.fluency_score),
            accuracy: Math.round(obj.sourceObj.accuracy_score),
            video: obj.video
        }
    })
    return res.code
}
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.readAsDataURL(file);

        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

// 播放音频
const playAudio = async () => {
    audioSrc.value = state.practoceList[currentPage.value - 1].wordFile

    nextTick(async () => {
        const palyModule = await import('@/assets/phoneticPractice/话筒效果-2.gif')
        playImgSrc.value = palyModule.default

        audioElement.value.play()

    })
}
//播放结束
const playEnded = async () => {
    const palyModule = await import('@/assets/phoneticPractice/声音@3x.png')
    playImgSrc.value = palyModule.default

}

//语音识别
const tapeClick = async () => {
    // practoceList[currentPage-1].words
    startRecording()//录音
    tapeShow.value = false
    const tapeModule = await import('@/assets/phoneticPractice/语音动画效果01.gif')
    tapeImgSrc.value = tapeModule.default
    iatRecorder.start()
}
//完成识别
const completeClick = async () => {

    tapeShow.value = true
    const tapeModule = await import('@/assets/phoneticPractice/录音@3x.png')
    tapeImgSrc.value = tapeModule.default
    iatRecorder.stop()
    stopRecording()//结束录音
    setTimeout(async () => {
        state.practoceList[currentPage.value - 1].sourceObj = iatRecorder.getScoreObj() || {}
        let num = state.practoceList[currentPage.value - 1].sourceObj.total_score
        if (num < 60) {
            scoreSrc.value = scoreSrcRed
        } else if (num > 60 && num < 80) {
            scoreSrc.value = scoreSrcYellow
        } else if (num > 80) {
            scoreSrc.value = scoreSrcGreed
        }
        state.practoceList[currentPage.value - 1].video = await blobToBase64(recordedChunks[0])
        if (active.value) {//自动
            next()
        }
    }, 1000);

}



const startRecording = async () => {
    try {
        recordedChunks = []
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        mediaRecorder = new MediaRecorder(stream);

        mediaRecorder.addEventListener('dataavailable', event => {
            recordedChunks.push(event.data);
        });

        mediaRecorder.start();
    } catch (error) {
        console.error('获取媒体流错误:', error);
    }
};

const stopRecording = () => {
    state.practoceList[currentPage.value - 1].recordedChunks = recordedChunks
    mediaRecorder.stop();
};

const playRecording = async () => {
    if (recordedChunks.length) {
        const blob = new Blob(recordedChunks, { type: 'audio/ogg' });
        const audioUrl = URL.createObjectURL(blob);
        const audio = new Audio(audioUrl);
        audio.play();
    } else if (state.practoceList[currentPage.value - 1].recordedChunks) {//点击上一个回显
        let chunk = state.practoceList[currentPage.value - 1].recordedChunks
        const blob = new Blob(chunk, { type: 'audio/ogg' });
        const audioUrl = URL.createObjectURL(blob);
        const audio = new Audio(audioUrl);
        audio.play();
    }

}

const blobToBase64 = (blob) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
    });
};


const switchManual = async () => {

    active.value = 0

}
const switchAutomatic = async () => {
    const bottomModule = await import('@/assets/phoneticPractice/形状@3x.png')
    bottomImgSrc.value = bottomModule.default
    active.value = 1
    automaticOverlay.value = false

}
const automaticPlay = async () => {
    if (isPlay.value) {
        const bottomModule = await import('@/assets/phoneticPractice/暂停@3x.png')
        bottomImgSrc.value = bottomModule.default
        isPlay.value = false
    } else {
        const bottomModule = await import('@/assets/phoneticPractice/形状@3x.png')
        bottomImgSrc.value = bottomModule.default
        isPlay.value = true
    }



}

const { practoceList, sourceObj } = toRefs(state)

</script>

<style scoped lang="scss">
.container-practice {
    height: 100%;
    text-align: center;

    .container-height {
        height: 46px;
    }

    .practice-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;

        // margin: 0 12px;
        // margin-top: 15px;
        .practice-top-currentPage {
            font-size: 16px;
            color: #0CB76C;

            span {
                color: #8E8E8E;
            }
        }

        .practice-top-slider {
            min-width: 234px;
            flex: 1;
            margin: 0 10px;

        }

        .practice-top-switch {

            // width: 72px;
            height: 22px;
            border-radius: 12px;
            font-size: 12px;
            background: #0CB76C;

            div {
                display: inline-block;
                width: 36px;
                height: 100%;
                color: #FFFFFF;
                text-align: center;
                line-height: 22px;
            }

            .active {
                height: 20px;
                color: #0CB76C;
                border: 1px solid #0CB76C;
                background: #FFFFFF;
                border-radius: 12px;
            }
        }
    }

    .container-text {
        margin-top: 20px;
        height: 310px;
        padding: 0 10px;
        text-align: left;
        font-family: PingFangSC, PingFang SC;
font-weight: 500;
font-size: 18px;
color: #333333;
line-height: 44px;
    }

    .practice-context {
        height: 165px;
        font-size: 14px;
        color: #8E8E8E;
        line-height: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;

        .practice-context-title {
            color: #333333;
            font-size: 32px;
            line-height: 45px;

        }

        .practice-context-context {
            margin-top: 10px;
        }

        .practice-context-bottom {
            margin-top: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;

            div {
                white-space: pre-line;
            }
        }

    }

    .practice-bottom {
        position: fixed;
        width: 100%;
        bottom: 0;
        height: 28px;
        background: #E7F8F0;
        color: #0CB76C;
        font-size: 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        line-height: 28px;

        .practice-bottom-img {
            width: 18px;
            height: 18px;
            margin-left: 20px;
        }

        .practice-bottom-start {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 80px;
            height: 20px;
            color: #0CB76C;
            border-radius: 18px;
            border: 1px solid #0CB76C;
        }
    }




}

.van-overlay {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    z-index: 200;

    .initialImg {
        width: 375px;
        height: 260px;
    }

    .initialDiv {
        width: 102px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        font-size: 12px;
        border: 1px solid #FFFFFF;
        color: #FFFFFF;
        border-radius: 18px;
        position: relative;
        top: 30px;
    }
}

.automaticOverlay {
    width: 345px;
    height: 184px;
    background: #FFFFFF;
    border-radius: 15px;
    color: #333333;
    font-size: 16px;
    line-height: 32px;

    .automaticOverlay-context {
        margin: 30px 20px;
    }

    .automaticOverlay-button {
        margin: 0 20px 30px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        div {
            width: 135px;
            height: 40px;
            line-height: 40px;
            text-align: center;
        }

        div:nth-child(1) {
            border: 1px solid #8E8E8E;
            border-radius: 22.5px;
            font-size: #333333;
        }

        div:nth-child(2) {
            border-radius: 22.5px;
            color: #FFFFFF;
            background: linear-gradient(to left, #29F19C, #02A1F9);
        }
    }

}

::v-deep .van-slider__button {
    display: none !important;
}

.autoRed {
    color: #FA192C !important;
}

.autoYellow {
    color: #FF9917 !important;
}

.autoGreed {
    color: #0CB76C !important;
}
</style>